package com.xiong.springsecurity.service.impl;

import com.xiong.springsecurity.domain.ResponseResult;
import com.xiong.springsecurity.domain.User;
import com.xiong.springsecurity.service.LoginService;
import com.xiong.springsecurity.utils.JwtUtil;
import com.xiong.springsecurity.utils.RedisCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *
 * @author XiongDa
 * @version 1.0.0
 * @belongsProject: SpringSecurity
 * @belongsPackage: com.xiong.springsecurity.service.impl
 * @since 2023/6/14 12:49
 **/

@Service
@RequiredArgsConstructor
@Slf4j
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;

    private final RedisCache redisCache;

    @Override
    public ResponseResult<Map<String, String>> login(User user) {
        // 1. 封装 Authentication 对象
        Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        // 2. 调用 AuthenticationManager 的 authentication 方法进行认证
        //    这里底层会去调用我们自己写的 UserDetailsServiceImpl 的 loadUserByUsername 方法, 如果密码正确
        //    并且 authenticate.getPrincipal() 可以拿到loadUserByUsername方法返回的 LoginUser 对象
        Authentication authenticate = authenticationManager.authenticate(authentication);

        log.info("==认证后的authenticate对象: {}", authenticate);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录错误");
        }

        // 3. 使用userId生成jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        // 4. 存入redis
        redisCache.setCacheObject("login:"+userId, loginUser);
        Map<String, String> map = new HashMap<>(1);
        map.put("token", jwt);
        return new ResponseResult<Map<String, String>>(200, "登入成功", map);
    }

}
